#!/usr/bin/python

'''
Created on 2012-9-30

@author: siloonuser
'''
import sys
import os,stat
import platform
import subprocess

import PySide
from PySide.QtGui import QApplication, QMainWindow, QTreeWidgetItem,QMessageBox
from PySide import QtGui

from ui_MainWindow import Ui_MainWindow
from SettingSaltKey import SettingSaltKeyDialog
from SettingEnviromentVar import SettingEnviromentVarDialog
from AppMain import AppMain
__version__ = '0.0.1'

class MainWindow(QMainWindow, Ui_MainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.setupUi(self)
        AppMain.loadCfgData()
        
        self.actionSaltKey.triggered.connect(self.openSaltKeySettingDialog)
        self.actionEnviromentVar.triggered.connect(self.openEnviromentVarSettingDialog)
       
        self.treeWidgetFile.itemSelectionChanged.connect(self.treeViewItemChangeHandler)
        self.initTreeView()
        self.initToolBar()
    
        self.pushButtonSave.clicked.connect(self.updatePasswordFileContent)
    def initTreeView(self):
        tree_items = self.createTreeItemsFromDir(AppMain.CFG_FILE_DIR)
        self.treeWidgetFile.clear()
        self.treeWidgetFile.addTopLevelItems(tree_items)
        
    def initToolBar(self):
        setPasswordAction = QtGui.QAction(QtGui.QIcon('icon/password.png'), 'Salt Password', self)
        setPasswordAction.triggered.connect(self.openSaltKeySettingDialog)
        self.toolbar = self.addToolBar('Password')
        self.toolbar.addAction(setPasswordAction)
        
        setEnvVarAction = QtGui.QAction(QtGui.QIcon('icon/settings.png'), 'Environment Variable', self)
        setEnvVarAction.triggered.connect(self.openEnviromentVarSettingDialog)
        self.toolbar = self.addToolBar('Environment Variable')
        self.toolbar.addAction(setEnvVarAction)
                
    def createTreeItemsFromDir(self,dir_path):
        tree_items = []
        for filename in os.listdir(dir_path):
            if filename[0:1] == "." :
                continue
            subpath = os.path.join(dir_path, filename)
            mode = os.stat(subpath)[stat.ST_MODE]
            tree_item = QTreeWidgetItem()
            tree_item.setText(0,filename)  
            tree_item.filePathInfo = subpath
            tree_item.isDir = False
            if stat.S_ISDIR(mode):
                tree_item.isDir = True
                child_items = self.createTreeItemsFromDir(subpath)
                tree_item.addChildren(child_items)
            
            tree_items.append(tree_item)
        return tree_items
                 
    def treeViewItemChangeHandler(self):
        #self.treeWidgetFile.CurrentChanged

        selected_item = self.treeWidgetFile.selectedItems()
        if len(selected_item) == 0:
            return
        selected_item = selected_item[0]
        if selected_item.isDir:
            return
        plain_text = self.decryptFile(selected_item.filePathInfo)
        self.textEditPlainText.setPlainText(plain_text)
    def decryptFile(self,file_path):
        cmd = 'java -classpath "%s" -jar %s -d -v -p %s %s' % (AppMain.CFG_JAVA_CMD_PATH,AppMain.CFG_JAVA_CMD_PATH,AppMain.CFG_SALT_KEY,file_path)
        #print cmd
        p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
        p.wait()
        plain_text = ''
        for line in p.stdout.readlines():
            plain_text = plain_text + line
       
        return plain_text
    
    def updatePasswordFileContent(self):
        selected_item = self.treeWidgetFile.selectedItems()
        if len(selected_item) == 0:
            return
        selected_item = selected_item[0]
        if selected_item.isDir:
            return
        plain_text =  self.textEditPlainText.toPlainText()
        plain_text = plain_text.strip()
        plain_text = plain_text.replace('\r\n','\n')
        #write to template file
        tmp_file = 'tmp_file.txt'
        open(tmp_file,'wb').write(plain_text)
        cmd = 'java -classpath "%s" -jar %s -p %s %s' % (AppMain.CFG_JAVA_CMD_PATH,AppMain.CFG_JAVA_CMD_PATH,AppMain.CFG_SALT_KEY,tmp_file)
        p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
        p.wait()
        open(tmp_file,'w').write('')
        encrypt_text = open('_pguse_tom_encrypt_out' + os.sep + tmp_file,'rb').read()
        
        confirm_plain_text = self.decryptFile('_pguse_tom_encrypt_out' + os.sep + tmp_file)
        confirm_plain_text = confirm_plain_text.strip()

       
        if confirm_plain_text == plain_text:
            open( selected_item.filePathInfo,'wb').write(encrypt_text)
            QMessageBox.about(self,"Info","Update Successfully") 
        else:
            QMessageBox.about(self,"Error","Update Failure")
               
    def openSaltKeySettingDialog(self):
        self.dialog = SettingSaltKeyDialog()
        self.dialog.show()
    def openEnviromentVarSettingDialog(self):
        self.dialog2 = SettingEnviromentVarDialog(self.enviromentVarSettingDialogCallBack)
        self.dialog2.show()
    def enviromentVarSettingDialogCallBack(self):
        self.initTreeView()
        
  
if __name__ == '__main__':
    app = QApplication(sys.argv)
    frame = MainWindow()
    frame.show()
    app.exec_()
